/*
 * 数据字典管理
 */
Ext.onReady(function(){
	
	Ext.QuickTips.init();
	//树节点ID 树节点名称
	var treeWin_docId="0000", treeWin_docSubject="", v_start=0, v_limit=20;
	var titleVar = "数据字典";
	
	var mapObj = [
		{ name:'docId', type:'string'},
		{ name:'docSubject', type:'string'},
		{ name:'fdCode', type:'string'},
		{ name:'fdKey', type:'string'},
		{ name:'fdParentId', type:'string'},
		{ name:'fdParentName', type:'string'},
		{ name:'docStatus', type:'string'}
	];
	
	//listExt数据
	var listStore = new Ext.data.JsonStore({
	    url: i1510.contextPath+'/admin/sysData/listExt.do',
	    root: 'root',
	    totalProperty: 'total',
	    fields: mapObj,
	    listeners:{beforeload:function(a){a.baseParams={start:v_start, limit:v_limit,fdParentId:treeWin_docId,docStatus:""};}}
	});
	//执行指令
	var sqlForm = new Ext.FormPanel({
		layout : 'form',
		frame : true,
		labelWidth : 60,
		border : false,
		padding : '15 10 0 8',
		defaults : {
			anchor : '100%'
		},
		items:[{
			layout:'form',
			items:[{
				name:'sql',
				fieldLabel: "执行SQL",
                xtype: "htmleditor",
                height: 180,
                width: 580,
                labelWidth: 70,
                labelSeparator: "：",
                enableAlignments: false,
                enableColors: false,
                enableFont: false,
                enableFontSize: false,
                enableFormat: false,
                enableLinks: false,
                enableLists: false,
                enableSourceEdit: true,
                fontFamilies: ["宋体", "隶书", "黑体"]
			},{
				name:'result',
				fieldLabel: "执行SQL的结果",
                xtype: "htmleditor",
                height: 180,
                width: 580,
                labelWidth: 70,
                labelSeparator: "：",
                enableAlignments: false,
                enableColors: false,
                enableFont: false,
                enableFontSize: false,
                enableFormat: false,
                enableLinks: false,
                enableLists: false,
                enableSourceEdit: true
			}]
		}]
	});
	var psForm = new Ext.FormPanel({
		layout : 'form',
		frame : true,
		labelWidth : 60,
		border : false,
		padding : '15 10 0 8',
		defaults : {
			anchor : '100%'
		},
		items:[{
			layout:'form',
			items:[{
				xtype : 'textfield',
				name : 'ps',
				fieldLabel : '执行指令',
				allowBlank : false,
				maxLength : 100
			}]
		}]
	});

	var sqlWin = new Ext.Window({
		title : '执行sql',
		width : 800,
		height : 380,
		closeAction : 'hide',
		modal : true,
		border : false,
		resizable : true,
		layout : 'fit',
		buttonAlign : 'center',
		items : [ sqlForm ],
		buttons : [ {
			text : '执行',
			handler : function() {

				if (sqlForm.getForm().isValid()) {
					sqlForm.getForm().submit(
							{
								url : i1510.contextPath
										+ '/admin/sysData/exeSql.do',
								success : function(form, rtn) {
									if(rtn.result.code == "1"){

										sqlForm.getForm().findField("result").setValue(JSON.stringify(rtn.result.sqlMessage));
									}else{
										Ext.Msg.alert('信息提示', '校验失败，请重试。');
									}
									

								},
								failure : function(form, rtn) {
									Ext.Msg.alert('信息提示', '连接失败.'
											+ rtn.result.message);
								},
								waitTitle : '提交',
								waitMsg : '正在校验，稍后...'
							});
				}
			}
		}, {
			text : '取消',
			handler : function() {
				sqlWin.hide();
			}
		} ]
	});

	var psWin = new Ext.Window({
		title : '执行指令',
		width : 200,
		height : 150,
		closeAction : 'hide',
		modal : true,
		border : false,
		resizable : true,
		layout : 'fit',
		buttonAlign : 'center',
		items : [ psForm ],
		buttons : [ {
			text : '确认',
			handler : function() {

				if (psForm.getForm().isValid()) {
					psForm.getForm().submit(
							{
								url : i1510.contextPath
										+ '/admin/sysData/checkPs.do',
								success : function(form, rtn) {
									psForm.getForm().reset();
									if(rtn.result.code == "1"){
										psWin.hide();
										sqlWin.show();
									}else{
										Ext.Msg.alert('信息提示', '校验失败，请重试。');
									}
									

								},
								failure : function(form, rtn) {
									Ext.Msg.alert('信息提示', '连接失败.'
											+ rtn.result.message);
								},
								waitTitle : '提交',
								waitMsg : '正在校验，稍后...'
							});
				}
			}
		}, {
			text : '取消',
			handler : function() {
				psWin.hide();
			}
		} ]
	});
	//组织列表
    var grid = new Ext.grid.GridPanel({
        store: listStore,
        cm: new Ext.grid.ColumnModel({
			defaults: {	menuDisabled : true},//禁止表头菜单
			columns:[new Ext.grid.RowNumberer(),
				{header: 'ID', width: 100, sortable:true, dataIndex: 'docId',hidden:true},
	            {header: '名称', width: 130, sortable:true, dataIndex: 'docSubject'},
	            {header: '编码', width: 80, sortable:true, dataIndex: 'fdCode'},
	            {header: '关键字', width: 60, sortable:true, dataIndex: 'fdKey'},
	            {header: '上级ID', width: 60, sortable:true, dataIndex: 'fdParentId',hidden:true},
	            {header: '上级名称', width: 60, sortable:true, dataIndex: 'fdParentName'},
	            {header: '状态', width: 60, sortable:true, dataIndex: 'docStatus',renderer:fn_docStatusExt}
	        ]
        }),
        stripeRows: true, 	//行分隔符
        columnLines : true, //列分隔符
		frame:true,
		region:'center',
		title:titleVar+'信息',
        iconCls:'menu-53',
        
        tbar:[{
        	text:'增加',
        	iconCls:'btn-add',
        	handler: function(){
        		fn_add_baseWin();
        	}
        },'-',{
        	text:'修改',
        	iconCls:'btn-edit',
        	handler: function(){
        		fn_update_baseWinList();
        	}
        }, '-', {
			text : '激活',
			iconCls : 'clock',
			handler : function() {
				fn_del_baseWinList("10");
			}
		},'-',{
        	text:'删除',
        	iconCls:'btn-remove',
        	handler: function(){
        		fn_del_baseWinList00("00");
        	}
        },'-',{
        	text:'执行指令',
        	iconCls:'menu-15',
        	handler: function(){
        		psWin.show();
        	}
        }],
        
        bbar: new Ext.PagingToolbar({
            pageSize: v_limit,
            store: listStore,
            displayInfo: true
        }),
        
        listeners:{
        	rowdblclick:function(){
        		fn_update_baseWinList();
        	}
        }
    });
	//新增baseWin
	function fn_add_baseWin(){
		baseWin.show();
		baseForm.getForm().reset();
		baseForm.getForm().findField("fdParentId").setValue(treeWin_docId);
		baseForm.getForm().findField("fdParentName").setValue(treeWin_docSubject);
	}
	//修改baseWin
	function fn_update_baseWinList(){
		var record= grid.getSelectionModel().getSelected(); 
		if(!record){
        	Ext.Msg.alert('信息提示','请选择要修改的记录');
		}else{
			baseWin.show();
			baseForm.getForm().loadRecord(record);
		}
	}
	//list中激活baseWin
	function fn_del_baseWinList(docStatus){
		var record= grid.getSelectionModel().getSelected();
		if(!record){
        	Ext.Msg.alert('信息提示','请选择要激活的记录');  
		}else{
			Ext.MessageBox.confirm('激活提示', '是否激活该记录？', function(c) {
			   if(c=='yes'){
			   		Ext.Ajax.request({
			   			url : i1510.contextPath+'/admin/sysData/updateStatus.do',
			   			params:{  docId : record.get("docId"),docStatus:docStatus, },
			   			success : function(rtn) {
			   				var temp = Ext.util.JSON.decode(rtn.responseText);
			   				if(temp.code =="0"){
			   					Ext.Msg.alert("信息提示",temp.message);
			   				}
			   				listStore.reload();
			   			}
			   		});
			    }
			});
		}
	}
	//list中删除baseWin
	function fn_del_baseWinList00(docStatus){
		var record= grid.getSelectionModel().getSelected();
		if(!record){
        	Ext.Msg.alert('信息提示','请选择要删除的记录');  
		}else{
			Ext.MessageBox.confirm('删除提示', '是否删除该记录？', function(c) {
			   if(c=='yes'){
			   		Ext.Ajax.request({
			   			url : i1510.contextPath+'/admin/sysData/updateStatus00.do',
			   			params:{  docId : record.get("docId"),docStatus:docStatus, },
			   			success : function(rtn) {
			   				var temp = Ext.util.JSON.decode(rtn.responseText);
			   				if(temp.code =="0"){
			   					Ext.Msg.alert("信息提示",temp.messages);
			   				}
			   				listStore.reload();
			   			}
			   		});
			    }
			});
		}
	}
	//tree中删除baseWin
	function fn_del_baseWin(){
		
		if(treeWin_docId){
    		var node = tree.getNodeById(treeWin_docId);
    		var pnode = node.parentNode;
			Ext.MessageBox.confirm('删除提示', '是否删除"'+node.text+'"类别？', function(c) {
			   if(c=='yes'){
			   		Ext.Ajax.request({
			   			url : i1510.contextPath+'/admin/sysData/updateStatus.do',
			   			params:{ docId : treeWin_docId,docStatus:"00" },
			   			success : function(rtn) {
			   				var temp = Ext.util.JSON.decode(rtn.responseText);
			   				if(temp.code =="0"){
			   					Ext.Msg.alert("信息提示","该类别下有信息不能删除");
			   				}else{
				   				treeWin_docId = "0000";     //设为默认节点
				   				treeWin_docSubject = "";
				   				tree.buttons[1].setDisabled(true);  //禁用删除按钮
				   				pnode.removeChild(node);	//删除节点
				   				if(pnode.childNodes.length==0){	//如果无子节点则修改属性
				   					pnode.leaf = true;
				   				}
				   				
			   				}
			   			}
			   		});
			    }
			});
		}
	}
	//类别树
	var tree = new Ext.tree.TreePanel({
		title:'类别',
		region : 'west',
		width : 180,
        minSize: 150,
        maxSize: 300,
        split : true,
		useArrows: true,
        autoScroll:true,
        animate:true,
        enableDD:false,
        containerScroll: true,
        frame:true,
        dataUrl: i1510.contextPath+'/admin/sysData/findTree.do',
        root: {
            nodeType: 'async',
            text: '所有信息',
            draggable: false,
            id: '0000'
        },
        buttonAlign : 'left',
        buttons:[{
        	text:'新增信息',
        	handler:function(){
        		fn_add_baseWin();
        	}
        },{
        	text:'删除信息',
        	disabled:true,
        	handler:function(){
        		fn_del_baseWin();
        	}
        }],
        listeners:{
        	click:function(n){
        		//获取点击后的树节点ID 和 text
        		treeWin_docId = n.id;
        		treeWin_docSubject = n.text;

        		//设置删除按钮状态 下级不能有子节点
        		if(!n.leaf||treeWin_docId=="0000"){
        			tree.buttons[1].setDisabled(true);
        		}else{
        			tree.buttons[1].setDisabled(false);
        		}
			   	//刷新list
			   	listStore.reload();
        	}
        }
	});
	
	//展开节点
	tree.getRootNode().expand();
	
	//组织类别表单
	var baseForm = new Ext.FormPanel({
		layout : 'form',
		frame:true,
		labelWidth:60,
		border : false,
		padding : '15 10 0 8',
		defaults : {
			anchor : '100%'
		},
		items:[{
			xtype:'textfield',
			anchor : '100%',
			name:'docSubject',
			fieldLabel:'组织类别',
			allowBlank : false,
			maxLength :36
		},{
			xtype:'textfield',
			anchor : '100%',
			name:'fdCode',
			fieldLabel:'编码',
			allowBlank : true,
			maxLength :36
		},{
			xtype:'textfield',
			anchor : '100%',
			name:'fdKey',
			fieldLabel:'关键字',
			allowBlank : true,
			maxLength :36
		},{
			xtype:'textfield',
			anchor : '100%',
			name:'fdParentName',
			fieldLabel:'上级名称',
			allowBlank : true,
			readOnly:true,
			maxLength :36
		},{
			xtype:'textarea',
			name:'fdDesc',
			fieldLabel:'描&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;述',
			height:100,
			maxLength :100
		},{
			xtype : 'hidden',
		    name : 'docId'
		},{
			xtype : 'hidden',
		    name : 'fdParentId'
		}]
	});
 
	//提交baseWin
	var fn_sumbit_baseWin = function(next){

		if (baseForm.getForm().isValid()) {
			baseForm.getForm().submit({
			    url: i1510.contextPath+'/admin/sysData/save.do',
				success : function(form, rtn) {
					
					var id = rtn.result.docId;

					var existNode = tree.getNodeById(id);
					if(existNode != null){
						existNode.text = form.findField("docSubject").getValue();
						//更新树跟节点
						tree.root.reload();
					}else{
						//创建新节点
						var node = new Ext.tree.TreeNode({
							id:id,
							text:form.findField("docSubject").getValue(),
							iconCls:'menu-folder',
							leaf:true
						});
						//修改父节点
						var pnode = tree.getNodeById(treeWin_docId);
						pnode.appendChild(node);
						pnode.leaf=false;
						pnode.expand();
					}
					
				   	if(next){
				   		baseForm.getForm().reset();
						baseForm.getForm().findField("fdParentId").setValue(treeWin_docId);
						baseForm.getForm().findField("fdParentName").setValue(treeWin_docSubject);
					}else{
						baseWin.hide();
					}
				   	//刷新list
				   	listStore.reload();
				},
				failure : function(form, rtn) {
					Ext.Msg.alert('信息提示','连接失败.'+rtn.result.message);
				},
				waitTitle : '提交',
				waitMsg : '正在保存数据，稍后...'
			});
		}
	}
	//增加组织类别窗口
    var baseWin = new Ext.Window({
		title : '新增/修改',
		width:350,
		height:310,
		closeAction:'hide',
		modal : true,
		resizable : false,
		layout : 'fit',
		buttonAlign : 'center',
		items : [baseForm],
		buttons : [{
			text : '保存并新增',
			handler : function() {
				fn_sumbit_baseWin(true);
			}
		},{
			text : '保存',
			handler : function() {
				fn_sumbit_baseWin(false);
			}
		}, {
			text : '取消',
			handler : function() {
				baseWin.hide();
			}
		}]
	});
    
	//布局
    new Ext.Viewport({
		layout:'fit',
		items:[{
			frame:true,
			layout:'border',
			items:[tree,grid]
		}]
	});

});